﻿using MediatR;
using SmartCity.ProcessEngine.API.Domain;
using SmartCity.ProcessEngine.API.ErrorCode;
using SmartCity.ProcessEngine.API.Infrastructrue.Extensions;
using SmartCity.ProcessEngine.API.Infrastructrue.Interfaces;
using SmartCity.ProcessEngine.API.Write.Applications.Commands;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.API.Write.Applications.CommandHandlers
{
    public class FormDetailCreatedCommandHandler : IRequestHandler<FormDetailCreatedCommand, APIResult<int>>
    {
        private readonly IBaseRespository<WF_FormDetail>? formdetailRep;

        public FormDetailCreatedCommandHandler(IBaseRespository<WF_FormDetail>? formdetailRep)
        {
            this.formdetailRep = formdetailRep;
        }

        public async Task<APIResult<int>> Handle(FormDetailCreatedCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            result.Code = APIResultCode.AddSuccess;
            result.Message= APIResultCode.AddSuccess.GetDescription();

            if (request.FormDetails.Count < 2)
            {
                throw new Exception("表单明细中至少得有两条数据");
            }

            //bool flag= request.FormDetails.Count(x => string.IsNullOrEmpty(x.FieldDesc) ||
            //string.IsNullOrEmpty(x.FieldName) || string.IsNullOrEmpty(x.FieldType)
            //|| string.IsNullOrEmpty(x.FieldControl)
            //);
            //if (flag)
            //{

            //}

            //找到旧的数据
            var list=formdetailRep.GetAll().Where(x=>x.FormNo==request.FormDetails[0].FormNo).ToList();
            //逻辑删除旧的数据
            list.ForEach(x =>
            {
                x.IsDelete = true;
            });
            



            //逻辑删除旧的数据
            request.FormDetails.ForEach(x =>
            {
                x.DetailId = YitIdHelper.NextId().ToString();
            });




            return await Task.FromResult(result);
        }
    }
}
